/*
Copyright (c) 2011, Stephane Albert
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the name of the organization nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL STEPHANE ALBERT BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include "global.h"

void pSleep(unsigned int sleepTime) {
    #ifdef WIN32
        Sleep(sleepTime);
    #else
        struct timespec time;
        if (sleepTime > 999) {
            div_t res;
            res = div(sleepTime, 1000);
            time.tv_sec = res.quot;
            time.tv_nsec = res.rem*1000000;
        }
        else
            time.tv_nsec = sleepTime*1000000;
        nanosleep(&time, NULL);
    #endif
}

bool isInputEmpty() {
    char curInput;
    do {
        curInput = std::cin.get();
    } while (curInput == ' ');
    if (curInput == '\n' || curInput == '\r') {
        return true;
    }
    else {
        std::cin.putback(curInput);
        return false;
    }
}

//Dirty but the easiest way to remove NL without trigering user input
void clearInputNL() {
    std::string unused;
    getline(std::cin, unused);
}

std::string intToString(int toConv, unsigned short minChars) {
    std::stringstream convert;
    if (minChars)
        convert << std::setfill('0') << std::setw(minChars) << toConv;
    else
        convert << toConv;
    return convert.str();
}

int stringToInt(const std::string& toConv) {
    std::stringstream convert(toConv);
    int res;
    convert >> res;
    return res;
}

std::string doubleToString(double toConv) {
    std::stringstream convert;
    convert << toConv;
    return convert.str();
}

bool moveFile(const std::string& oldPath, const std::string& newPath, bool overwrite) {
    if (rename(oldPath.c_str(), newPath.c_str()) != 0) {
        //Rename/Moving failed, file must be in a different FS: copying
        std::ifstream oldFile;
        std::ofstream newFile;
        oldFile.open(oldPath.c_str(), std::ios_base::binary);
        if (!oldFile.is_open())
            return false;
        if (!overwrite) {
            //Rename file to avoid overwriting
            std::string renamedNewFile = newPath;
            std::ifstream tempFile(newPath.c_str(), std::ios_base::binary);
            for (int i=1; tempFile.is_open(); ++i) {
                tempFile.close();
                if (i == 100)
                    return false;
                renamedNewFile = newPath;
                renamedNewFile.append(".renamed.");
                renamedNewFile.append(intToString(i, 2));
                tempFile.open(renamedNewFile.c_str(), std::ios_base::binary);
            }
            tempFile.close();
            newFile.open(renamedNewFile.c_str(), std::ios_base::binary);
        }
        else
            newFile.open(newPath.c_str(), std::ios_base::binary);
        if (!newFile.is_open())
                return false;
        newFile << oldFile.rdbuf();
        //Detect filesize mismatch (disk full)
        if (newFile.tellp() != (oldFile.seekg(0, std::ios_base::end)).tellg()) {
            newFile.close();
            remove(newPath.c_str());
            return false;
        }
        oldFile.close();
        remove(oldPath.c_str());
    }
    return true;
}
